<?php

//TODO: Get user creation date and use instead of taken date if necessary
require_once 'phpFlickr.php';
require_once 'apikey.php';
require_once 'helpers.php';

class DatemodsSearch
{
    public $status;
    private $status_count = 1;
    private $year;
    private $phpFlickr;
    private $page_count;
    private $last_page = 0;
    private $all_pages = array();
    private $photoslistcomplete = false;
	private $resultlistcomplete = false;
    public $done = false;
    public $results;
    
    public function getStatus()
    {
        return $this->status;
    }
    
    public function setStatus( $update )
    {
       $this->status = $this->status . $this->status_count++ . " " . $update . "\n";
    }
    
// doNext() will implement the next step in getting the entire list of duplicates.    
    public function doNext()
    {
        $result = '';
        if (!$this->photoslistcomplete){
            $result = $this->getPhotoList($this->last_page + 1);       
        } 
		elseif (!$this->resultlistcomplete) {
            $result = $this->makeResultList();
        } 
		
        if(!$this->done){
            $this->setStatus($result);
        }
        else {
            return;
        }
    }
    
    public function __construct($form)
    {
		$this->phpFlickr = new phpFlickr(API_KEY, API_SECRET);
        //$this->phpFlickr->enableCache("db", "mysql://stconrad:TitgP47@mysql.seantconrad.com/flickrocd");
        
        $this->year = $form->getValue('year');
        $this->flickrid = $form->getValue('flickrid'); 
		$this->phpFlickr->auth("delete", true);
        $this->usertimeoffset = $form->getValue('timezone');
        $this->timezoneoffset = $this->usertimeoffset*60*60;

    }
// getPhotoList() will use the Flickr Search API to get the photos and 
// necessary metadate for the page number passed in. By default, it gets page 1.
// When finished, the flag $photoslistcomplete is set to true, and $all_photos
// contains a list of all the phot    
    private function getPhotoList($page)
    {
        if('' !=  $this->year) {
            $photos = $this->phpFlickr->photos_search(array(
                "user_id"=>"me",
                "sort"=>"date-taken-asc",
                "min_taken_date"=>$this->year . "-01-01 00:00:01",
                "max_taken_date"=>($this->year + 1). "-01-01 00:00:01",
                "page"=>$page,
                "per_page"=>"50"));
        }
        else {
            $photos = $this->phpFlickr->photos_search(array(
                "user_id"=>"me",
                "sort"=>"date-taken-asc",
                "page"=>$page,
                "per_page"=>"50"));
        }
        
        if(!is_array($photos)){
            throw new Exception("phpFlickr Error: " . $this->phpFlickr->error_code . " " . $this->phpFlickr->error_msg . " " . implode ("+", array(
            "user_id"=>"me",
            "sort"=>"date-taken-asc",
            "min_taken_date"=>$this->year . "-01-01 00:00:01",
            "max_taken_date"=>($this->year + 1). "-01-01 00:00:01",
            "page"=>$page,
            "per_page"=>"500")));
        }

        $this->page_count = $photos['pages'];
        $this->last_page = $page;
        
        if (0 == $this->page_count) {
			$this->photoslistcomplete = true;
			return "No photos found for those parameters.";
		}

		$DateTimeOriginal = '';
        foreach ($photos['photo'] as $photo)
		{
			// EXIF appears to be the same as the date in the Flicr API,
			// so not getting it for now.
			/*$EXIF = $this->phpFlickr->photos_getExif($photo['id']);
			foreach($EXIF['exif'] as $key => $value)
            {
				if(is_array($value)) {
					if($value['tag'] == "DateTimeOriginal" || $value['label'] == "Date and Time (Original)") {
						$DateTimeOriginal = $value['raw'];
						break;
					}
				}
			}*/
			
			$photoinfo = $this->phpFlickr->photos_getInfo($photo['id']);
            $photo_date_uploaded = isset($photoinfo['dates']['posted']) ? $photoinfo['dates']['posted'] : '';
			$photo_date_taken = isset($photoinfo['dates']['taken']) ? $photoinfo['dates']['taken'] : '';
            
            // Flickr stores date posted as a timestamp (877521600) but 
            // date taken as a string with no timezone (1997-10-22 12:00:00).
            // We convert the timestamp to the user's timezone and assume the
            // date taken is in the same. This will cause some inconsistencies 
            // if the user is has set his camera for DST. 
			
			// HACK: For some reason the PHP date() function keeps converting my timestamp
            // to the server timezone. To get around this, after adjusting by the offset
            // we use gmdate() to ironicaly keep the string at the user's timezone.
			$local_photo_date_uploaded = gmdate("Y-m-d H:i:s", $photo_date_uploaded + $this->timezoneoffset); // Add offset to get local time 

			$this->all_photos[$photo['id']] = array("photo"=>$photo, "API_date_posted"=>$local_photo_date_uploaded, "API_date_taken"=>$photo_date_taken, "EXIF_date_taken"=>$DateTimeOriginal);
			$DateTimeOriginal = '';

        }
        if($this->page_count == $this->last_page){
            $this->photoslistcomplete = true;
        }
        return "Fetched page " . $this->last_page . " of " . $this->page_count . " of the photo list.";
    }

// makeResultList() cycles throught the photos and generates
// a result list of sets of photos with dates to be updated.
    private function makeResultList()
    {
		
		foreach($this->all_photos as $key=>$photoinfo)
        {
            echo ($photoinfo['API_date_posted']. " " . $photoinfo['API_date_taken']);
            if($photoinfo['API_date_posted'] != $photoinfo['API_date_taken'] ) {
				                
                $photo = $photoinfo['photo'];
                $id = $photo['id'];
                $url = "http://www.flickr.com/photos/" . $photo['owner'] . "/" . $photo['id'];
                $thumb_url = $this->phpFlickr->buildPhotoURL($photo, "thumbnail");//Can we not hit Flickr?
                $title = $photo['title'];
                if(isset($photo['description'])){
                    $description = $photo['description'];
                }
                else {
                    $description =  '';
                }
				
				$photoarray = array(
				"id"=>$key, 
				"url"=>$url,
				"title"=>$title,
				"description"=>$description,
				"thumbnail"=>$thumb_url,
				"API_date_posted"=>$photoinfo['API_date_posted'],
				"API_date_taken"=>$photoinfo['API_date_taken']);
				
				$this->results[$key] = $photoarray;
			}
        } 

        $this->resultlistcomplete = true;
        $this->done = true;
		echo describeAnidatedArray($this->results);
        return "Done.";
    }

// updateDates($duplist) takes a list of photos from
// the results property and modifies the posted date,
// setting it to be the same as the taken date.

// TO DO: updateDates() needs to run in chunks for large sets
    public function updateDates()
    {
        // Confirm we have permissions with Flickr
        $this->phpFlickr->auth("delete", true);
        
        $count = 0;

        foreach ($this->results as $id=>$photoinfo) {

            //$this->phpFlickr->photos_setDates($id, strtotime($photoinfo['API_date_taken']));
            
			// We must translate date to GMT timestamp before updating
			$new_photo_date_uploaded=strtotime($photoinfo['API_date_taken']) - $this->timezoneoffset ; 

            echo ("Setting photo " . $id ." posted date to " . $new_photo_date_uploaded . " which is:<br/>");
            
			echo ($photoinfo['API_date_posted'] . " to " . gmdate("Y-m-d H:i:s", $new_photo_date_uploaded) . "<br/>");
            
            $count++;
            if ($this->phpFlickr->getErrorMsg()) {
                throw new Exception("phpFlickr Error: ID:" . $id . " " . $this->phpFlickr->error_code . " " . $this->phpFlickr->error_msg);
            }
        }
        
        return ($count . " photo(s) successfully updated!");
    }
}
?>